package com.timous.web;


import com.timous.service.BlogService;
import com.timous.service.TagService;
import com.timous.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    String temp;

    @Autowired
    private BlogService blogService;

    //注入类型
    @Autowired
    private TypeService typeService;

    //注入标签
    @Autowired
    private TagService tagService;

    @GetMapping("/about")
    public String about(){

        return "blogabout";

    }

    @GetMapping("/")
    public String index(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.DESC)
                                Pageable pageable, Model model) {

        //拿到分页的数据
        model.addAttribute("page", blogService.listBlog(pageable));
        //获取分类的信息
        model.addAttribute("types", typeService.listTypeTop(6));
        //获取标签的信息
        model.addAttribute("tags", tagService.listTagTop(10));
        //推荐博客
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));
        System.out.println("--------index--------------");
        return "index";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
//        int i = 9/0;
//        String blog = null;
//        if(blog == null){
//            throw new NotFoundException("博客不存在");
//        }
        model.addAttribute("blog", blogService.getAndConvert(id));

        System.out.print(blogService.getBlog(id));

        return "blogdetails";
    }

    @GetMapping("search")
    public String search(@PageableDefault(size = 2, sort = {"id"}, direction = Sort.Direction.DESC)
                                 Pageable pageable, Model model, String query) {

        if (query != null) {
            temp = query;
            model.addAttribute("query", query);
        } else {
            query = temp;
            model.addAttribute("query", temp);
        }

        model.addAttribute("page", blogService.listBlog("%" + query + "%", pageable));

        System.out.print(query);


        return "search";
    }

    @GetMapping("blogabout")
    public String blogabout() {

        return "blogabout";
    }

    //动态加载最下面的文章
    @GetMapping("/footer/newblog")
    public String newBlogs(Model model){

        model.addAttribute("newblogs" , blogService.listRecommendBlogTop(3));

        return "index :: newblogList";
    }

}
